package com.zdsoft.crm.controller.auth;

import java.util.UUID;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zdsoft.crm.entity.auth.SysRole;
import com.zdsoft.crm.service.auth.ISysRoleService;
import com.zdsoft.crm.vo.AjaxVo;
import com.zdsoft.crm.vo.PageVo;

@Controller
@RequestMapping("auth/role")
public class RoleController {

	@Autowired
	ISysRoleService roleService;
	
	 //分页查询
	@GetMapping("/list")
	public ModelAndView list(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		
		PageVo list=roleService.findPage(pageNum, pageSize);
		return new ModelAndView("auth/role/list.html", "list", list); 
	}
	 // 跳转到添加页面
	@GetMapping
	public String saveUi(){
		return "auth/role/save.html";
	}
	
	/**
	 * 添加页面保存按钮
	 * 后台验证
	 * @param sysUser
	 * @returns
	 */
	@PostMapping
	public ModelAndView save(@Valid SysRole role,BindingResult result,RedirectAttributes redirectAttributes) {
		ModelAndView mav = new ModelAndView("redirect:/auth/role/list");
		if (result.hasErrors()) {
			mav = new ModelAndView("redirect:/common/err");
			redirectAttributes.addFlashAttribute("errorList", result.getAllErrors());
			return mav;
		}
		role.setId(UUID.randomUUID().toString().replace("-", ""));
		roleService.save(role);
		return mav;
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ResponseBody	//页面如果用ajax请求的话，这里必须与页面一致，而且这里调用的delete注解，页面的type也要设置成delete;
	public AjaxVo delete(@PathVariable("id") String id){
		roleService.deleteRole(id);
		return new AjaxVo().setErrorMsg("0");
	}
	
	@GetMapping("/{id}")
	public ModelAndView updateUi(@PathVariable("id") String id){
		return new ModelAndView("auth/role/update.html", "role", roleService.findById(id));
	}
	
	 // 修改页面保存按钮
	@PostMapping("/{id}")
	public String update(SysRole sysRole){
		roleService.update(sysRole);
		return "redirect:/auth/role/list";
	}
	
}
